<?php
namespace app\base\controller;
/* *
 * 后台基类
 * */
class AdminController extends ErrorController{
	protected $appID = 'admin';
	public $layout = 'app/admin/view/layout' ; //layout

	public function __construct(){
		if(!isset( $_SESSION )) session_start();
		$this->checkLogin();
		parent::__construct();
		$this->appconfig = config(APP_NAME);
		$this->website_id = $this->userInfo['website_id'];
		$this->admin_id = $this->userInfo['website_id'];
        if($this->website_id ){
            $this->website = model('website','admin')->sitename($this->website_id);
            $this->sitename = '/ <span class="fn-fb red">'.$this->website.'</span>';
        }else{
            $this->website = model('website','admin')->_select($this->website_id);
        }
	}
	
	//权限验证
	protected function checkLogin(){
		//不需要登录验证的页面
		$noLogin = array('default'=>array('login','verify','logout'),);	

		//如果当前访问是无需登录验证，则直接返回		
		if( isset($noLogin[CONTROLLER_NAME]) && in_array(ACTION_NAME, $noLogin[CONTROLLER_NAME]) ){	
			return true;
		}
		//没有登录,则跳转到登录页面
		if( !$this->isLogin() ){
			$this->redirect( url('admin/default/login') );
		}else{
			$rel = $this->isAuth();
			if(!$rel){
				$this->pageMsg('您没有权限访问本次操纵,请联系管理员,增加权限');
				return true;
			}
		}
		return true;
	}

	//权限判断
	protected function isAuth(){
		$groupid = intval($_SESSION[ $this->appID . '_userInfo' ]['groupid']);
		$group = model('auth','admin')->_find(array('id'=>$groupid));  //权限组
		if($group['auth_value']){
			$auth = json_decode($group['auth_value'],TRUE);
			if($auth[0] == -1)return true;  //超级权限
			foreach ($auth as $key => $value) {
				$route = explode('_', $value, 3);
				$routeNum = count($route);
				switch ($routeNum) {
					case 1:
						$url = APP_NAME;
						break;
					case 2:
						$url = APP_NAME.'_'.CONTROLLER_NAME;
						break;
					case 3:
						$url = APP_NAME.'_'.CONTROLLER_NAME.'_'.ACTION_NAME;
						break;
				}
				if(in_array($url,$auth)){
					return true;
				}
			}
			return false;
		}else{
			return false;
		}
	}

	//判断是否登录
	protected function isLogin(){
		if( empty( $_SESSION[ $this->appID . '_userInfo' ] ) ){
			return false;
		}else{
			$this->userInfo = $_SESSION[ $this->appID . '_userInfo' ];
			return true;
		}
	}
	
	//设置登录
	protected function setLogin( $userInfo ){
		$_SESSION[ $this->appID . '_userInfo' ] = $userInfo;
	}
	
	//退出登录
	protected function clearLogin( $url='' ){
		$_SESSION[ $this->appID . '_userInfo' ] = NULL;
		if( !empty($url) ){
			$this->redirect( $url );
		}
		return true;
	}
}